/************** Bread Crumb ******************/
/**
To Use in any Xform
1. Have a rich text on the form with Id as "breadcrumb_container".
2. Initialise breadcrumb as "initializeBreadCrumb()" in "Form_InitDone()".
*/
function initializeBreadCrumb() {
	system.addListener("onapplicationstatechange", manageCrumbs);
}

function manageCrumbs(appObj) {
	if (appObj.applicationState == "loaded") {
		var applicationDef = system.containers[appObj.applicationId].guiRepresentation.applicationDefinition;
		var applicationLevel = cordys.getNodeText(applicationDef, ".//*[local-name()='level']");

		if (!applicationDef || !applicationLevel) return;
		applicationLevel = (cordys.getNodeText(applicationDef, ".//*[local-name()='name']") == 'Home') ? 0 : applicationLevel;

		var newAppLevel = parseInt(applicationLevel);
		var breadCrumb_Container = document.getElementById("breadcrumb_container");
		var currentAppLevel = breadCrumb_Container.currentAppLevel ? breadCrumb_Container.currentAppLevel : -1;
		if (newAppLevel > currentAppLevel) {
			//Add crumb with New AppLevel
			addCrumb(applicationDef, newAppLevel);
		} else if (newAppLevel <= currentAppLevel) {
			//Remove Everything till new AppLevel
			resetCrumb(newAppLevel, currentAppLevel);
			addCrumb(applicationDef, newAppLevel);
		}
		breadCrumb_Container.currentAppLevel = newAppLevel;
	}
}

function addCrumb(applicationDef, appLevel) {
	var breadCrumbContainer = document.getElementById("breadcrumb_container");
	var crumbHolder = document.createElement("span");
	crumbHolder.id = "crumb" + appLevel;
	crumbHolder.appDef = applicationDef;
	applicationCaption = (cordys.selectXMLNode(applicationDef, ".//*[local-name()='name']") != null) ? cordys.getNodeText(applicationDef, ".//*[local-name()='name']") : cordys.getNodeText(applicationDef, ".//*[local-name()='caption']");;
	var crumbStruct = "<a href='#' onclick='openApplicationFrmCrumb(event)'>" + applicationCaption + "</a>";
	var extender = "<label>&gt;</label>";
	crumbHolder.innerHTML = (appLevel == 0) ? crumbStruct : extender + crumbStruct;
	breadCrumbContainer.appendChild(crumbHolder);
}

function resetCrumb(newAppLevel, currentAppLevel) {
	for (var i = currentAppLevel; i >= newAppLevel; i--) {
		var crumb = document.getElementById("crumb" + i);
		if (crumb) crumb.parentNode.removeChild(crumb);
	}
}

function openApplicationFrmCrumb(eventObject) {
	var eventObject = eventObject ? eventObject : window.event;
	var crumbItem = cordys.getEventTarget(eventObject).parentNode;
	application.select(crumbItem.appDef, null, frameAutoSize);
}

function clearCrumbdata() {
	document.getElementById('breadcrumb_container').innerHTML = "";
}